from django.views import View

from User.models import Order, UserVip, UserCoupon
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequiredUser


class PayView(LoginRequiredUser, View):
    """ 支付信息 """

    @Req.getJson
    def post(self, request):
        """ 支付 """
        oid = request.json_dict.get('oid')
        payType = request.json_dict.get('payType')
        vipId = request.json_dict.get('vipId')
        couponId = request.json_dict.get('couponId')

        user = request.user.user

        if payType not in Order.PayType.list():
            return Res.Json(Res.ParamErr,msg="错误的支付类型Id")

        userVip, userCoupon = None, None

        if vipId:
            userVip = UserVip.objects.filter(id=vipId, user=user).first()
            if not userVip:
                return Res.Json(Res.ParamErr,msg="错误的会员卡Id")
        if couponId:
            userCoupon = UserCoupon.objects.filter(id=couponId, user=user).first()
            if not userCoupon:
                return Res.Json(Res.ParamErr,msg="错误的优惠券Id")

        order = Order.objects.filter(user=user, oid=oid).first()
        if not order:
            return Res.Json(Res.ParamErr,msg="错误的订单Id")

        state, msg = order.canPay(payType, user, userVip, userCoupon)
        if not state:
            return Res.Json(Res.Warn, msg=msg)  # 非支付状态

        status = order.pay(user, payType, userVip, userCoupon)
        return Res.Json(Res.OK, status=status)
